import requests
from typing import List, Dict, Optional, Any
import logging
from datetime import datetime, timedelta

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S"
)
logger = logging.getLogger(__name__)


class SimpleNotesFetcher:
    """简化版达人笔记获取器 - 只获取最近5篇笔记"""

    def __init__(self, base_url: str, secret: str):
        """
        初始化工具
        :param base_url: API基础地址
        :param secret: 认证secret
        """
        self.base_url = base_url.rstrip("/")
        self.secret = secret
        self.session = requests.Session()

        # 配置请求头
        self.headers = {
            "Content-Type": "application/json; charset=utf-8",
            "secret": self.secret
        }

    def fetch_recent_5_notes(self, user_uuid: str, days: int = 180) -> Dict[str, Any]:
        """
        获取达人最近5篇笔记的完整内容
        :param user_uuid: 达人唯一标识
        :param days: 查询最近多少天，默认为60天
        :return: 包含笔记完整内容的结果
        """
        try:
            # 计算时间范围 - 增加到60天
            end_time = datetime.now()
            start_time = end_time - timedelta(days=days)
            time_format = "%Y-%m-%d %H:%M:%S"

            # 准备请求参数
            request_body = {
                "userUuid": user_uuid,
                "size": 5,  # 只获取5篇
                "publicTimeStart": start_time.strftime(time_format),
                "publicTimeEnd": end_time.strftime(time_format)
            }

            api_path = "/platform/agent/homepage/listNoteByUserUuid"
            request_url = f"{self.base_url}{api_path}"

            logger.info(f"开始请求达人最近5篇笔记，user_uuid: {user_uuid}")
            logger.info(f"时间范围: {start_time.strftime(time_format)} 至 {end_time.strftime(time_format)}")
            logger.info(f"请求体: {request_body}")

            # 发送POST请求
            response = self.session.post(
                url=request_url,
                headers=self.headers,
                json=request_body,
                timeout=15
            )
            response.raise_for_status()

            # 解析响应
            response_json = response.json()
            logger.info(f"完整API响应: {response_json}")  # 打印完整响应以便调试

            api_code = response_json.get("code", "")

            if api_code != "200":
                error_msg = response_json.get("msg", "API返回业务错误")
                logger.error(f"API业务错误: {error_msg}")
                return {
                    "status": "error",
                    "code": api_code,
                    "msg": error_msg,
                    "data": None
                }

            # 获取原始笔记数据
            raw_notes = response_json.get("data", [])
            logger.info(f"获取到 {len(raw_notes)} 篇笔记")

            # 返回完整的原始数据，不做过多处理
            return {
                "status": "success",
                "code": api_code,
                "msg": "获取笔记数据成功",
                "data": {
                    "user_uuid": user_uuid,
                    "note_count": len(raw_notes),
                    "raw_notes": raw_notes  # 返回原始数据
                }
            }

        except requests.exceptions.HTTPError as e:
            status_code = getattr(e.response, "status_code", None)
            error_msg = f"HTTP请求错误: {str(e)}"
            logger.error(f"HTTP错误详情: {e.response.text}")  # 打印HTTP错误响应体
            return {
                "status": "error",
                "code": str(status_code) if status_code else "400",
                "msg": error_msg,
                "data": None
            }
        except Exception as e:
            error_msg = f"请求错误: {str(e)}"
            logger.error(f"异常详情: {error_msg}", exc_info=True)
            return {
                "status": "error",
                "code": "500",
                "msg": error_msg,
                "data": None
            }


def display_notes_complete(notes_data: Dict):
    """完整显示笔记内容和图片信息"""
    if not notes_data or notes_data["status"] != "success":
        print("获取数据失败")
        if notes_data:
            print(f"错误信息: {notes_data['msg']}")
            print(f"错误代码: {notes_data['code']}")
        return

    data = notes_data["data"]
    raw_notes = data["raw_notes"]

    print(f"\n达人 {data['user_uuid']} 的最近 {data['note_count']} 篇笔记:")
    print("=" * 80)

    if data["note_count"] == 0:
        print("未查询到任何笔记，可能的原因:")
        print("1. 该达人在这段时间内没有发布笔记")
        print("2. 用户UUID不正确")
        print("3. API接口权限或配置问题")
        return

    for i, note in enumerate(raw_notes, 1):
        print(f"\n第 {i} 篇笔记:")
        print("-" * 50)

        # 基础信息
        print(f"笔记ID: {note.get('id', 'N/A')}")
        print(f"发布时间: {note.get('publicTime', 'N/A')}")
        print(f"标题: {note.get('title', 'N/A')}")
        print(f"简介: {note.get('description', 'N/A')}")

        # 笔记类型信息
        print(f"笔记形式: {note.get('modelType', 'N/A')}")
        print(f"笔记类型: {note.get('noteType', 'N/A')} (1=商业笔记, 0=非商业笔记)")
        print(f"是否广告: {note.get('isAdvertise', 'N/A')}")
        print(f"笔记分类: {note.get('noteClass', 'N/A')}")
        print(f"二级标签: {note.get('secondaryLabel', 'N/A')}")
        print(f"笔记价格: {note.get('notePrice', 'N/A')}")

        # 互动数据
        print("\n互动数据:")
        print(f"  点赞数: {note.get('likedCount', 0)}")
        print(f"  收藏数: {note.get('collectedCount', 0)}")
        print(f"  评论数: {note.get('commentsCount', 0)}")
        print(f"  分享数: {note.get('sharedCount', 0)}")
        print(f"  阅读量: {note.get('readNum', 0)}")
        print(f"  曝光量: {note.get('exposureNum', 0)}")
        print(f"  互动量: {note.get('interactionNum', 0)}")

        # 预测数据
        print(f"  预估阅读量: {note.get('readPredict', 0)}")
        print(f"  预估曝光量: {note.get('exposurePredict', 0)}")

        # 图片信息 - 重点显示
        images_str = note.get('imagesList', '')
        if images_str:
            images_list = [img.strip() for img in images_str.split(",") if img.strip()]
            print(f"\n图片信息 (共 {len(images_list)} 张):")
            for j, img_url in enumerate(images_list, 1):
                print(f"  图片 {j}: {img_url}")
        else:
            print("\n图片信息: 无图片")

        # 视频信息
        video_url = note.get('videoUrl', '')
        if video_url:
            print(f"视频链接: {video_url}")

        print("-" * 50)


if __name__ == "__main__":
    # 配置参数
    BASE_URL = "https://zongsing.com/prod-api"
    SECRET = "e572009a47a77c1d88774e93b4b1cd96"
    TARGET_USER_UUID = "6549e5640000000004008716"

    # 初始化工具并获取笔记 - 增加到60天范围
    fetcher = SimpleNotesFetcher(base_url=BASE_URL, secret=SECRET)
    result = fetcher.fetch_recent_5_notes(user_uuid=TARGET_USER_UUID, days=180)

    # 显示结果
    print("=" * 80)
    print("达人最近5篇笔记数据获取结果")
    print("=" * 80)

    if result["status"] == "success":
        display_notes_complete(result)
    else:
        print(f"错误: {result['msg']}")
        print(f"错误代码: {result['code']}")

    print("=" * 80)